unit DatabaseDefinition;

interface

uses
  EntityDefinition, OmniXML;

type

  TDatabaseDefinition = class
  private
    fEntityDefinitions: TEntityDefinitions;
  public
    constructor Create(); overload;
    constructor Create(aXMLParser: IXMLDocument); overload;
    destructor Destroy(); override;
    procedure addEntityDefinition(aEntityDefinition: TEntityDefinition);
    function getEntityDefinitionByIndex(aIndex: integer): TEntityDefinition;
    function getEntityDefinitionByName(aName: String): TEntityDefinition;
    function getLength(): integer;
    procedure initialize(aXMLParser: IXMLDocument);
  end;

implementation

uses
  SysUtils;

{ TDatabaseDefinition }

procedure TDatabaseDefinition.addEntityDefinition(aEntityDefinition
  : TEntityDefinition);
begin
  SetLength(fEntityDefinitions, length(fEntityDefinitions) + 1);
  fEntityDefinitions[High(fEntityDefinitions)] := aEntityDefinition;
end;

function TDatabaseDefinition.getLength: integer;
begin
  Result := length(fEntityDefinitions);
end;

procedure TDatabaseDefinition.initialize(aXMLParser: IXMLDocument);
var
  tables: IXMLNodeList;
  fEntityDefinition: TEntityDefinition;
  table: IXMLNode;
  iTable: integer;
begin
  SetLength(fEntityDefinitions, 0);
  tables := aXMLParser.DocumentElement.SelectNodes('table');
  for iTable := 0 to tables.length - 1 do
  Begin
    table := tables.Item[iTable];
    fEntityDefinition := TEntityDefinition.Create(table);
    fEntityDefinition.prepareOuters(tables);
    addEntityDefinition(fEntityDefinition);
  End;
end;

constructor TDatabaseDefinition.Create(aXMLParser: IXMLDocument);
begin
  initialize(aXMLParser);
end;

constructor TDatabaseDefinition.Create;
begin
  SetLength(fEntityDefinitions, 0);
end;

destructor TDatabaseDefinition.Destroy;
begin

  inherited;
end;

function TDatabaseDefinition.getEntityDefinitionByIndex(aIndex: integer)
  : TEntityDefinition;
begin
  if (aIndex < 0) OR (aIndex > getLength() - 1) then
  begin
    raise Exception.Create(className + ': out of range');
  end;
  Result := fEntityDefinitions[aIndex];
end;

function TDatabaseDefinition.getEntityDefinitionByName(aName: String)
  : TEntityDefinition;
var
  i: integer;
begin
  Result := nil;
  for i := 0 to getLength() - 1 do
  begin
    if (Trim(fEntityDefinitions[i].getName()) = Trim(aName)) then
    begin
      Result := fEntityDefinitions[i];
      break;
    end;
  end;
end;

end.
